$.get("./bases.json", function name(data) {

    var info = collectInfos(data.bases);

    var levels = ["全部"].concat(info.levels.sort(function (l1, l2) {
        return l2 - l1
    }));

    var tags = ['全部'].concat(info.tags);

    levels.forEach(function (level, index) {
        $('.levels').append($(`<span class="level" ${index==0 ? 'select' : ''}>${level}</span>`))
    });

    tags.forEach(function (tag, index) {
        $('.tags').append($(`<span class="tag" ${index==0 ? 'select' : ''}>${tag}</span>`))
    });

    select();

    $('.level').on("click", function() {
        if ($(this).attr('select') == '') return;

        $('.level[select]').removeAttr('select');
        $(this).attr('select', '');

        select();
    });

    $('.tag').on("click", function() {
        if ($(this).attr('select') == '') return;

        $('.tag[select]').removeAttr('select');
        $(this).attr('select', '');

        select();
    });

    function select() {
        var level = $('.level[select]').text();
        var tag = $('.tag[select]').text();

        var bases = data.bases.slice();

        var levelFilter = function (base) {
            return level === '全部' ? true : base.level == level;
        }
        
        var tagFilter = function (base) {
            return tag === '全部' ? true : base.tag.some(function (ta) {
                return ta == tag;
            })
        }
        
        bases = bases.filter(levelFilter).filter(tagFilter);

        updateBases(bases);

    };

    
})



function copyLink(url) {
    var copyInput = document.getElementById("copyInput");
    copyInput.value = url;
    copyInput.select();
    copyInput.setSelectionRange(0, 99999); /*For mobile devices*/

    /* Copy the text inside the text field */
    document.execCommand("copy");
    alert("复制成功");
}

function openLink(url) {
    window.open(url, '_self');
}

function updateBases(bases) {

    var html = '';
    bases.forEach(function (base) {

        var url = base.url;

        html += `
            <div class="base" style="background-image: url(./imgs/${base.id}.jpg)">
                <div class="btn-group">
                    <a href="#" onclick="copyLink('${url}')" class="btn">复制链接</a>
                    <a href="#" onclick="openLink('${url}')" class="btn">打开链接</a>
                </div>
            </div>
        `;

    })

    $(".bases").html(html);
}

function collectInfos(bases) {
    var levels = [], tags = [];
    var levelMap = {}, tagMap = {};

    bases.forEach(function(base) {
        var level = base.level,
            tag = base.tag;

        if (!levelMap[level]) {
            levels.push(level);
            levelMap[level] = 1;
        }

        tag.forEach(function(ta) {
            if (!tagMap[ta]) {
                tagMap[ta] = 1;
                tags.push(ta);
            }
        })

    });

    return {
        levels: levels,
        tags: tags
    }
}